import wx
import sqlite3
import os , sys
from threading import Thread
import time
import logging
from hash2 import *
from pubsub import pub #pypubsub
from hash_gui import *
from hashThread import *
from inc import *
from upgrade import *
from mf2 import *
import random
#pip install pypubsub wxpython tqdm reedsolo

########################################################################
class MF1(MyFrame1):
    def __init__(self, parent):
        super().__init__(parent)
        self.Centre(wx.BOTH)
        self.Bind(wx.EVT_CLOSE, self.onExit)
        pub.subscribe(self.upStautsBar1,"upStautsBar1")
        p1(self)
    def upStautsBar1(self,msg):
        self.m_statusBar1.SetStatusText(msg)

    def onExit(self, event):

        dlg = wx.MessageDialog(None, u"确定退出？", u"确定退出",
                               wx.YES_NO | wx.ICON_QUESTION)
        if dlg.ShowModal() == wx.ID_YES:
            sys.exit(0)
        dlg.Destroy()
class p1(MyPanel1):
    def __init__(self, parent):
        super().__init__(parent)
        pub.subscribe(self.uptextCtrl1,"uptextCtrl1")
        pub.subscribe(self.changeButton,"hashThreadStatus")
        pub.subscribe(self.upProgressBar1,"upProgressBar1")
        pub.subscribe(self.upProgressBar2,"upProgressBar2")
        pub.subscribe(self.upStaticText1,"upStaticText1")
        self.nowtime=time.time()
        self.db=None
        self.info={
            'root':None,
            'filelist': [],
            'filecount' : 0,
            'dircount' :0,
            'complete': 0,
        }

        self.root=r"D:\\"
        self.db = sqlite3.connect(self.root+"/"+logfilename+".db", check_same_thread=False)
        
    def __del__(self):
        print(f"p1_del")
        pass
    def upProgressBar1(self,msg):
        self.m_gauge5.SetValue(msg)
    def upProgressBar2(self,msg):
        self.m_gauge6.SetValue(msg)
    def changeButton(self,msg):
        if(msg):
            self.m_button1.Disable()
            self.m_button3.Disable()
            self.m_button2.SetLabel("暂停")
        else:
            self.m_button1.Enable()
            self.m_button3.Enable()
            self.m_button2.SetLabel("退出")
    def onExit(self, event):
        if(self.m_button2.GetLabel()=="退出"):
            dlg = wx.MessageDialog(
                None, u"确定退出？", u"确定退出", wx.YES_NO | wx.ICON_QUESTION)
            if dlg.ShowModal() == wx.ID_YES:
                sys.exit(0)
            dlg.Destroy()
        else:
            wx.CallAfter(pub.sendMessage,"stopHashThread",msg=True)
        event.Skip()

    def uptextCtrl1(self,msg):
        self.m_textCtrl1.AppendText("{t} {msg}\n".format(t=time.strftime('%Y-%m-%d %H:%M:%S'),msg=msg))
    def upStaticText1(self,msg):
        self.m_staticText1.SetLabel(msg)

    # Virtual event handlers, overide them in your derived class

    def onStart( self, event ):

        if(self.db == None):
            dlg = wx.MessageDialog(None, u"请选择目录", '',
                                   wx.ICON_WARNING)
            dlg.ShowModal()
            dlg.Destroy()
            return False
        HashThread(db=self.db,rootpath=self.root)
        event.Skip()
    def onVerify(self, event):

        if(self.db == None):
            dlg = wx.MessageDialog(None, u"请选择目录", '',
                                   wx.ICON_WARNING)
            dlg.ShowModal()
            dlg.Destroy()
            return False
        HashThread(db=self.db,rootpath=self.root,hashTable="checkslist",writeTable="checks",expirationDate=getConfig(self.db,'expirationDate'))
        event.Skip()

    def onDirC(self, event):

            self.root = event.GetPath()
            print(self.root)
            try:
                self.db = sqlite3.connect(self.root+"\\"+logfilename+".db", check_same_thread=False)
                #db = sqlite3.connect(":memory:", check_same_thread=False)
                cur = self.db.cursor()
                result = cur.execute(
                    "select * from sqlite_master where type = 'table' and name = 'list'")
                row = result.fetchall()
                logging.info(len(row))
            except:
                msg("数据库创建失败！")
                return False
            if(len(row) > 0):
                r = msg("文件列表已存在，是否更新文件列表？", "更新文件列表",
                        wx.YES_NO | wx.ICON_INFORMATION)
                if(r == wx.ID_YES):

                    trySql(self.db,'DROP table IF EXISTS list')
                    trySql(self.db,'DROP table IF EXISTS dirs')
                    trySql(self.db,
                        'create table list (path varchar(256) NOT NULL primary key, hash varchar(2),  checks varchar(2))')
                    trySql(self.db,
                        'create table dirs (path varchar(256) NOT NULL primary key, hash varchar(2),  checks varchar(2))')

                else:
                    result = cur.execute("select count(path) from dirs")  # 清空文件夹列表
                    row = result.fetchone()
                    self.info['dircount'] = row[0]
                    result = cur.execute("select count(path) from list")  # 清空文件列表
                    row = result.fetchone()
                    self.info['filecount'] = row[0]
                    wx.CallAfter(pub.sendMessage,"upStaticText1",msg=f"目录总数：{self.info['dircount'] }  文件总数：{self.info['filecount'] }")
                    return True
            else:
                if (not createDB(self.root)):
                    logging.error("数据表创建出错！")
                    msg("数据表创建出错！")
            createView(self.root)
            upgrade(f"{self.root}\\{logfilename}.db")
            ScanThread(rootpath=self.root)
            # CheckFile()
            event.Skip()
    def onInfo(self, event):
        w2=None
        list_=[u"新增文件",u"丢失文件",u"重复文件",u"差异文件",u"查看记录",u"文件恢复"]
        for i in list_:
            w2=wx.FindWindowByLabel(i)
            if (isinstance(w2,f2)):  break

        if(self.db == None):
            dlg = wx.MessageDialog(None, u"请选择目录", '',
                                   wx.ICON_WARNING)
            dlg.ShowModal()
            dlg.Destroy()
            return False
        if(w2 != None):
            w2.Destroy()
        try:
            w2 = f2(None,self.root)
            p2(w2,self.root)
            w2.Show()
        except BaseException as e:
            logging.error(e)
            w2 = None

class test1(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.start()
    def run(self):
        n=0
        while(1):
            hash = hash_()
            n=n+1
            hash.update(f"{n}\t{time.time()}{random.random()}".encode())
            # time.sleep(0.1)
            pub.sendMessage("uptextCtrl1",msg=f"{n}\t{hash.hexdigest().upper()}")
            pub.sendMessage("upStautsBar1",msg=str(time.time()))
            # wx.CallAfter(pub.sendMessage,"uptextCtrl1",time.time())
if __name__ =="__main__":
    app=wx.App()
    f_=MF1(None)
    f_.Show()
    app.MainLoop()
